package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Description 菜品相关接口
 * @Author shh
 * @Date 2025-10-05
 */
@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        //调用aliOssUtil的upload方法，上传文件到OSS
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名:{}", originalFilename);
        //构造新文件名，避免文件名重复
        //UUID.randomUUID().toString() 随机生成一个唯一的字符串
        //originalFilename.substring(originalFilename.lastIndexOf(".")) 获取原始文件名的后缀
        String url = null;
        try {
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //新文件名,如何得到的,随机字符串+原始文件名的后缀
            url = aliOssUtil.upload(file.getBytes(), fileName);//上传文件到OSS,返回文件的url
        } catch (IOException e) {
            log.error("文件上传失败:{}", e.getMessage());
            return Result.error("文件上传失败");
        }
        return Result.success(url);
    }
}
